package com.fanketly.module_safe.activity

import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.drake.brv.BindingAdapter
import com.drake.brv.listener.DefaultItemTouchCallback
import com.drake.brv.utils.linear
import com.drake.brv.utils.setup
import com.fanketly.core_lib_bean.POSITION_INCREMENT
import com.fanketly.module_safe.R
import com.fanketly.module_safe.data.model.SafeUrlModel
import com.fanketly.module_safe.databinding.ActivitySafeBinding
import com.fanketly.module_safe.domain.SafeRequester
import com.fanketly.module_safe.domain.UrlMemoEvent
import com.fanketly.module_safe.ui.dialog.SafeAddUrlPopupView
import com.lxj.xpopup.XPopup
import fanketly.core.extension.addOnBRV
import fanketly.core.lib.base.ui.BaseMVIActivity
import fanketly.core.lib.router.module.safe.SafeRouter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Route(path = SafeRouter.PATH_MAIN, group = SafeRouter.GROUP)
class SafeActivity : BaseMVIActivity<ActivitySafeBinding, SafeRequester>() {
    private var mClipboardManager: ClipboardManager? = null
    private lateinit var mAdapter: BindingAdapter
    private var mMemoList: MutableList<SafeUrlModel> = mutableListOf()
    private var mSelectPosition = -1

    override fun initView() {
        //        if (FingerprintUtils.supportFingerprint(this)) {
//            FingerprintUtils.showBiometricPrompt(this) {
        binding.safeInclude.coreUiLlTopBar.setBackgroundColor(getColor(R.color.green_200))
        binding.safeInclude.coreUiBtnBack.setOnClickListener { finish() }
        binding.safeInclude.coreUiTitle.text = getString(R.string.core_ui_safe_url)
//        binding.safeInclude.coreUiTitle.setTextColor(R.color.white)
        mClipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        lifecycleScope.launch {
            mAdapter = binding.rvSafe.linear().setup {
                addType<SafeUrlModel>(R.layout.safe_item_conent)
                onClick(R.id.safe_item_parent, R.id.safe_item_left, R.id.safe_item_right) {
                    when (it) {
                        R.id.safe_item_parent -> {
                            LogUtils.i(getModel<SafeUrlModel>().url)
                            val intent = Intent()
                            intent.action = Intent.ACTION_VIEW
                            intent.data = Uri.parse(getModel<SafeUrlModel>().url)
                            startActivity(Intent.createChooser(intent, "请选择浏览器"))
                        }
                        R.id.safe_item_left -> {
                            mSelectPosition = bindingAdapterPosition
                            val model = mMemoList[bindingAdapterPosition]
                            showAddPopup(model.url, model)
                        }
                        else -> {
                            val model = mMemoList[bindingAdapterPosition]
                            val deleteMemo = UrlMemoEvent.DeleteMemo()
                            deleteMemo.sourceModel = model
                            mViewModel.input(deleteMemo)
                            mMemoList.removeAt(bindingAdapterPosition)
                            mAdapter.notifyItemRemoved(bindingAdapterPosition)
                        }
                    }
                }
                itemTouchHelper = ItemTouchHelper(object : DefaultItemTouchCallback() {
                    override fun onDrag(
                        source: BindingAdapter.BindingViewHolder,
                        target: BindingAdapter.BindingViewHolder
                    ) {
                        //移动之后的位置
                        val sourcePosition = source.absoluteAdapterPosition//进行拖拽item的新位置
                        val sourceModel = mMemoList[sourcePosition]
                        val targetPosition =
                            target.absoluteAdapterPosition//targetPosition 是target的移动方向的位置
                        val targetModel = mMemoList[targetPosition]
                        LogUtils.d(targetPosition, sourcePosition)
//                        LogUtils.d("target:" + targetModel.name)
//                        LogUtils.d("source:" + sourceModel.name)
                        when (sourcePosition) {
                            0 -> {
                                sourceModel.position = targetModel.position / 2
                            }
                            modelCount - 1 -> {
                                sourceModel.position = targetModel.position + POSITION_INCREMENT
                            }
                            else -> {
                                val position =
                                    if (sourcePosition + 1 != targetPosition) sourcePosition + 1
                                    else sourcePosition - 1
                                val model = mMemoList[position]
                                sourceModel.position =
                                    (model.position + targetModel.position) / 2
                            }
                        }
                        val switchMemo = UrlMemoEvent.SwitchMemo()
                        switchMemo.sourceModel = sourceModel
                        mViewModel.input(switchMemo)
                    }
                })

            }
            mAdapter.models = mMemoList
            binding.safeBtnAdd.setOnClickListener {
                showAddPopup(null)
            }

        }
//            }
//        }
    }

    //            val safeRepo = SafeRepo()
//            mMemoList.forEachIndexed { index, safeUrlModel ->
//                safeUrlModel.position = INCREMENT * (index + 1)
//                LogUtils.d(safeUrlModel.position)
//                safeRepo.update(safeUrlModel)
//            }
    override fun initData() {
    }

    override fun onInput() {
        mViewModel.input(UrlMemoEvent.GetMemoList())
    }

    override fun onOutput() {
        mViewModel.output(this) {
            when (it) {
                is UrlMemoEvent.AddMemo -> mAdapter.notifyItemInserted(mMemoList.addOnBRV(it.memo!!))
                is UrlMemoEvent.GetMemoList -> {
                    mAdapter.addModels(it.memoList)
                }
                is UrlMemoEvent.SwitchMemo -> if (!it.isSuccess) {
                    ToastUtils.showShort("交换失败")
                }
                is UrlMemoEvent.EditMemo -> if (!it.isSuccess) {
                    ToastUtils.showShort("编辑失败")
                } else {
                    mAdapter.notifyItemChanged(mSelectPosition)
                }
                is UrlMemoEvent.DeleteMemo -> if (!it.isSuccess) {
                    ToastUtils.showShort("删除失败")
                }
            }
        }
    }


    override fun onResume() {
        super.onResume()
        if (mClipboardManager != null) {
            getClipboard()
        } else {
            mClipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            getClipboard()
        }
    }


    private fun showAddPopup(url: String?, model: SafeUrlModel? = null) {
        with(XPopup.Builder(this@SafeActivity)) {
            asCustom(SafeAddUrlPopupView(this@SafeActivity, url, model?.name) { url, n ->
                lifecycleScope.launch(Dispatchers.IO) {
                    if (model == null) {
                        mViewModel.input(
                            UrlMemoEvent.AddMemo(
                                SafeUrlModel(
                                    url,
                                    n,
                                    if (mMemoList.size == 0) POSITION_INCREMENT else POSITION_INCREMENT * mMemoList.size + 1
                                )
                            )
                        )
                    } else {
                        val editMemo = UrlMemoEvent.EditMemo()
                        model.name = n
                        model.url = url
                        editMemo.sourceModel = model
                        mViewModel.input(editMemo)
                    }
                }
            }).show()
        }
    }

    private fun getClipboard() {
        //当view绘制完成后再进行读取
        window.decorView.post() {
            mClipboardManager!!.primaryClip?.let {
                if (it.itemCount > 0) {
                    val s = it.getItemAt(0).text.toString()
                    if (s.isNotEmpty() && RegexUtils.isURL(s)) showAddPopup(s)
                }
            }
        }
    }
}
